package net.study;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class TestdataDao {
	public List<TestdataDto> getList() {
		List result = new ArrayList();
		try {
			// getConnection
			Connection conn = getConnection();
			String sql = "select id, foo, bar from testdata" ;
			// Statement
			PreparedStatement pstmt = conn.prepareStatement(sql);
			// ResultSet
			ResultSet rs = pstmt.executeQuery();
			// while
			while (rs.next()) {
				TestdataDto dto = new TestdataDto();
				dto.setId(rs.getString(1));
				dto.setFoo(rs.getString(2));
				dto.setBar(rs.getString(3));
				result.add(dto);
			}
			// rs.close
			rs.close();
			// pstmt.close
			pstmt.close();
			// conn.close
			conn.close();
		} catch (Exception e) {
			// TODO: handle exception
		}
		finally {

		}
		return result;
	}

	private Connection getConnection() throws NamingException, SQLException {

		Context initContext = new InitialContext();
		Context envContext  = (Context)initContext.lookup("java:/comp/env");
		DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");
		Connection conn = ds.getConnection();

		return conn;
	}
}
